import {createSlice, PayloadAction} from "@reduxjs/toolkit";

export interface UserState {
    isLogin: boolean;
    userInfo: {
        name: string
        id: string
    };
    isShowLoginDialog: boolean;
}

const initialState: UserState = {
    isLogin: window.localStorage.getItem("token") !== null,
    userInfo: JSON.parse(window.localStorage.getItem("userInfo") ?? "{}"),
    isShowLoginDialog: false,
};

export const userSlice = createSlice({
    name: "user",
    initialState,
    reducers: {
        login: (state,action: PayloadAction<()=>void>) => {
            state.isLogin = true;
            state.userInfo = JSON.parse(
                localStorage.getItem("userInfo") ?? "{}",
            );
            action.payload()
        },
        logout: (state) => {
            localStorage.removeItem("token");
            state.isLogin = false;
        },
        showLoginDialog: (state) => {
            state.isShowLoginDialog = true;
        },
        hideLoginDialog: (state) => {
            state.isShowLoginDialog = false;
        }
    },
});

export const {login, logout, showLoginDialog, hideLoginDialog} = userSlice.actions;
export default userSlice.reducer;
